import { http } from '../../utils/http'
import { ref } from 'vue'
import { loadEnv } from '@build/index'

import * as signalR from '@microsoft/signalr'
import router from '@/router'

import { useLoginAccountStoreWithOut } from '@/store/modules/login'
import { DetectEnd, UA } from '@/utils/wecom'

const loginAccountStore = useLoginAccountStoreWithOut()
const ua = DetectEnd();

// const signalR = require("@microsoft/signalr")
const connection = ref<signalR.HubConnection>()

export default {
  async buildConnection() {        
    const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL, VITE_USE_MOCK } = loadEnv()
    const baseURL = VITE_USE_MOCK
      ? ''
      : process.env.NODE_ENV === 'production'
        ? VITE_PROXY_DOMAIN_REAL
        : VITE_PROXY_DOMAIN
    
    if (connection.value?.state == signalR.HubConnectionState.Connected) {
      await connection.value.stop();
    }
    
    connection.value = new signalR.HubConnectionBuilder()
      .withUrl(`${baseURL}/api/notify`, {
        accessTokenFactory: () => loginAccountStore.getToken,
        withCredentials: true,
      })
      .configureLogging(signalR.LogLevel.None)
      .withAutomaticReconnect()
      .build();
  },
  async startConnect() {
    try {
      await connection.value?.start();
    } catch (error) {
      if (ua != UA.WeComApp && ua != UA.WeComClient) {
        router.push('/login')

        return false;
      }

      // 如果是WeCom客户端，则启动OAuth免密认证      
      return false;
    }
    
    return true;
  },
  attachToHub(methodName: string, newMethod: (...args: any[]) => void) {
    connection.value?.on(methodName, newMethod);
  },
  detachFromHub(methodName: string) {        
    connection.value?.off(methodName);
  },
  async addToGroupAsync(groupName: string) {
    try {
      await connection.value?.invoke('AddToGroup', groupName);
    } catch (error) {
      
    }    
  },
  async getRoleCode() {
    return http.request<string[]>('get', '/api/permission/role');
  },
  getConnection() {
    return connection.value;
  }
}